package com.hispot.projection.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hispot.projection.R;
import com.hispot.projection.bluetooth.BluetoothClientService;
import com.hispot.projection.bluetooth.BluetoothTools;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final int MODE_CONTROLLER = 0;
    private static final int MODE_MOUSE = 1;
    private static final int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 1;
    private static final String SHAREPREFERENCE_NAME = "projection";


    private ImageView power_btn;
    private ImageView action_menu;
    private ImageView voice_add;
    private ImageView voice_down;
    private ImageView voice;
    private ImageView control_mode;

    private TextView no_bonded_device;

    private View controller_remind;
    private View mouse_remind;
    private View loading_view;
    private View connect_rl;
    private View connect_btn_rl;
    private View main_ll;
    private View action_bar_rl;

    private View action_bar_device_btn;
    private View action_bar_about_btn;


    private ImageView home;
    private ImageView back;
    private ImageView menu;

    private Animation circle_anim;

    private MyReceiver myReceiver;
    private IntentFilter intentFilter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent(this, BluetoothClientService.class);
        startService(intent);
        init();
        myReceiver = new MyReceiver();
        intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothTools.ACTION_BLUETOOTH_CONNECTING);
        intentFilter.addAction(BluetoothTools.ACTION_BLUETOOTH_NO_BONDED_DEVICE);
        intentFilter.addAction(BluetoothTools.ACTION_CONNECT_ERROR);
        intentFilter.addAction(BluetoothTools.ACTION_PAIRING_SUCC);
        intentFilter.addAction(BluetoothTools.ACTION_CONNECT_SUC);
    }

    private void init() {
        power_btn = findViewById(R.id.power_btn);
        action_menu = findViewById(R.id.action_menu);
        voice_add = findViewById(R.id.voice_add);
        voice_down = findViewById(R.id.voice_down);
        voice = findViewById(R.id.voice);
        control_mode = findViewById(R.id.control_mode);
        loading_view = findViewById(R.id.loading_view);

        no_bonded_device = findViewById(R.id.no_bonded_device);

        controller_remind = findViewById(R.id.controller_remind);
        mouse_remind = findViewById(R.id.mouse_remind);
        connect_rl = findViewById(R.id.connect_rl);
        connect_btn_rl = findViewById(R.id.connect_btn_rl);
        main_ll = findViewById(R.id.main_ll);
        action_bar_rl = findViewById(R.id.action_bar_rl);

        action_bar_device_btn = findViewById(R.id.action_bar_device_btn);
        action_bar_about_btn = findViewById(R.id.action_bar_about_btn);

        home = findViewById(R.id.home);
        back = findViewById(R.id.back);
        menu = findViewById(R.id.menu);


        power_btn.setOnClickListener(this);
        action_menu.setOnClickListener(this);
        voice_add.setOnClickListener(this);
        voice_down.setOnClickListener(this);
        voice.setOnClickListener(this);
        control_mode.setOnClickListener(this);
        connect_btn_rl.setOnClickListener(this);

        action_bar_device_btn.setOnClickListener(this);
        action_bar_about_btn.setOnClickListener(this);

        home.setOnClickListener(this);
        back.setOnClickListener(this);
        menu.setOnClickListener(this);

        main_ll.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (action_bar_rl.getVisibility() == View.VISIBLE) {
                    action_bar_rl.setVisibility(View.GONE);
                    return false;
                }
                return true;
            }
        });
        circle_anim = AnimationUtils.loadAnimation(this, R.anim.circle_anim);
        LinearInterpolator lin = new LinearInterpolator();
        circle_anim.setInterpolator(lin);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.action_menu:
                action_bar_rl.setVisibility(View.VISIBLE);
                break;
            case R.id.power_btn:
                break;
            case R.id.voice_add:
                break;
            case R.id.voice_down:
                break;
            case R.id.voice:
                break;
            case R.id.control_mode:
                SharedPreferences sharedPreferences = getSharedPreferences(SHAREPREFERENCE_NAME, MODE_PRIVATE);
                int mode = sharedPreferences.getInt("control_mode", MODE_CONTROLLER);
                if (mode == MODE_CONTROLLER) {
                    control_mode.setBackgroundResource(R.drawable.mouse_mode);
                    controller_remind.setVisibility(View.GONE);
                    mouse_remind.setVisibility(View.VISIBLE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putInt("control_mode", MODE_MOUSE);
                    editor.commit();
                } else {
                    control_mode.setBackgroundResource(R.drawable.controller_mode);
                    controller_remind.setVisibility(View.VISIBLE);
                    mouse_remind.setVisibility(View.GONE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putInt("control_mode", MODE_CONTROLLER);
                    editor.commit();
                }
                break;
            case R.id.connect_btn_rl:
                connecteDevice();
                break;
            case R.id.home:
                break;
            case R.id.back:
                break;
            case R.id.menu:
                break;
            case R.id.action_bar_device_btn:
                //todo 跳转到蓝牙列表界面
                break;
            case R.id.action_bar_about_btn:
                //todo 跳转到关于界面
                break;
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                connecteDevice();
            } else {
                Toast.makeText(MainActivity.this, "蓝牙权限未开启", Toast.LENGTH_SHORT).show();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onResume() {
        registerReceiver(myReceiver, intentFilter);
        if (checkPermission()) {
            if (!BluetoothClientService.IS_CONNECTED) {
                connecteDevice();
            } else {
                showControllView();
            }
        } else {
            connect_rl.setVisibility(View.VISIBLE);
            loading_view.clearAnimation();
            loading_view.setVisibility(View.GONE);
        }
        super.onResume();
    }

    @Override
    protected void onPause() {
        unregisterReceiver(myReceiver);
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        Intent intent = new Intent(this, BluetoothClientService.class);
        stopService(intent);
        super.onDestroy();
    }

    private void connecteDevice() {
        SharedPreferences sharedPreferences = getSharedPreferences(SHAREPREFERENCE_NAME, MODE_PRIVATE);
        String addr = sharedPreferences.getString("addr", null);
        String name = sharedPreferences.getString("name", "");
        if (addr != null && !addr.equals("")) {
            no_bonded_device.setText(name);
            Intent intent = new Intent(BluetoothTools.ACTION_BLUETOOTH_START);
            sendBroadcast(intent);
        }
    }

    private boolean checkPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                        MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION);
                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.READ_CONTACTS)) {
                    Toast.makeText(this, "需要通过蓝牙连接到设备才能使用此功能", Toast.LENGTH_SHORT).show();
                }
                return false;
            }
        }
        return true;
    }

    private void showControllView() {
        loading_view.clearAnimation();
        connect_rl.setVisibility(View.GONE);
        SharedPreferences sharedPreferences = getSharedPreferences("control_share", MODE_PRIVATE);
        int mode = sharedPreferences.getInt("control_mode", MODE_CONTROLLER);
        if (mode == MODE_CONTROLLER) {
            control_mode.setBackgroundResource(R.drawable.controller_mode);
            controller_remind.setVisibility(View.VISIBLE);
            mouse_remind.setVisibility(View.GONE);
        } else {
            control_mode.setBackgroundResource(R.drawable.mouse_mode);
            controller_remind.setVisibility(View.GONE);
            mouse_remind.setVisibility(View.VISIBLE);
        }
    }

    private class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BluetoothTools.ACTION_BLUETOOTH_NO_BONDED_DEVICE)) {
                connect_rl.setVisibility(View.VISIBLE);
                loading_view.clearAnimation();
                loading_view.setVisibility(View.GONE);
            }
            if (action.equals(BluetoothTools.ACTION_BLUETOOTH_CONNECTING)) {
                connect_rl.setVisibility(View.VISIBLE);
                loading_view.setVisibility(View.VISIBLE);
                loading_view.startAnimation(circle_anim);
            }
            if (action.equals(BluetoothTools.ACTION_CONNECT_ERROR)) {
                connect_rl.setVisibility(View.VISIBLE);
                loading_view.clearAnimation();
                loading_view.setVisibility(View.GONE);
            }

            if (action.equals(BluetoothTools.ACTION_PAIRING_SUCC)) {
                SharedPreferences sharedPreferences = getSharedPreferences(SHAREPREFERENCE_NAME, MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("addr", intent.getStringExtra("addr"));
                editor.putString("name", intent.getStringExtra("name"));
                editor.commit();
            }

            if (action.equals(BluetoothTools.ACTION_PAIRING_SUCC)) {
                showControllView();
            }
        }
    }

}
